﻿using System.Net;

namespace XYS.Core.Util.Helper;

/// <summary>
/// ip地址帮助类
/// </summary>
public static class IPAddressHelper
{
    /// <summary>
    /// 是否为内网IP
    /// </summary>
    /// <param name="ipAddress"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static bool IsPrivateIP(string ipAddress)
    {
        if (IPAddress.TryParse(ipAddress, out var ip))
        {
            byte[] bytes = ip.GetAddressBytes();
            switch (ip.AddressFamily)
            {
                case System.Net.Sockets.AddressFamily.InterNetwork:
                    // IPv4
                    return (bytes[0] == 10) || bytes[0] == 172 ||
                       (bytes[0] == 192 && bytes[1] == 168) ||
                       (bytes[0] == 127); // 回环地址
                case System.Net.Sockets.AddressFamily.InterNetworkV6:
                    // IPv6 (可以扩展以支持内网IPv6地址)
                    return false; // 根据需要处理IPv6
                default:
                    return false;
            }
        }
        throw new ArgumentException("无效的IP地址");
    }
}
